package com.fire.security.controller;


import com.fire.security.core.page.TableDataInfo;
import com.fire.security.domain.CurrentUser;
import com.fire.security.domain.Result;
import com.fire.security.domain.User;
import com.fire.security.service.UserService;
import com.fire.security.utils.MD5Util;
import com.fire.security.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;



import java.util.List;


@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    //注入redis模板
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /*
     * 条件分页查询
     * */
    @GetMapping ("/selectByConditions")
    public TableDataInfo userList( User user) {
        startPage();
        List<User> list = userService.findByConditions(user);
        return getDataTable(list);
    }
    /*
     * 用户更新
     * */
    @PutMapping("/updateUser")
    public Result updateUser(User user) {
        Result result = userService.updateUser(user);
        return result;
    }
    @PostMapping("/updateUserPassword")
    public Result updateUserPassword(String oldPassword, String newPassword, String userId) {
        User currentUser = userService.findById(userId);
        System.out.println(currentUser);
        if (MD5Util.hmacSign(oldPassword).equals(currentUser.getPassword())){
            User user = new User();
            user.setId(currentUser.getId());
            user.setPassword(MD5Util.hmacSign(newPassword));
            Result result = userService.updateUser(user);
            return result;
        }else {
            return Result.err(0,"原密码错误");
        }
    }

    /*
     * 添加用户
     * */
    @PostMapping ("/register")
    public Result insertUser(User user,String code) {
        if(!stringRedisTemplate.hasKey(code)){
            return Result.err(Result.CODE_ERR_BUSINESS, "验证码不正确！");
        }
        stringRedisTemplate.delete(code);
        user.setId(IdUtils.simpleUUID());
        user.setIsMerchant(0);
        user.setPassword(MD5Util.hmacSign(user.getPassword()));
        Result result=userService.insertUser(user);
        return result;

    }

    /*
     * 删除用户
     * */
    @PostMapping("/deleteUserById")
    public Result deleteUserById(String id) {
        Result result = userService.deleteUserById(id);
        return result;

    }

}

